<template>
  <view class="flex_header_main whov" @click.stop="initCountdown">
    <!-- <view class="flex_header_main whov" :style="{ paddingTop: statusBarHeight + 'px' }" @click.stop="initCountdown"> -->
    <view class="flex_header">
      <TitleTime :title="pointName || '智能寄存柜'" />
    </view>
    <view class="flex_main" style="position: relative">
      <view class="success_box">
        <view class="success_img"> <img src="@/assets/img/success.png" /></view>
        <view class="succexx_text success_label">开门成功</view>
        <view class="succexx_text">
          <text class="succexx_text1">请及时取出自己的物品，并<text class="succexx_text2">随手关门!</text></text>
        </view>
      </view>

      <view class="time"> <text class="ret_text" @click="onClick" style="margin-right: 20rpx;">返回 </text> {{ countdown }} 秒 </view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick, onUnmounted, watch } from 'vue'
  import TitleTime from '@/components/TitleTime.vue'
  import { onLoad } from '@dcloudio/uni-app' // 使用uni-app的定时器API

  const pointName = ref('')

  // 倒计时相关变量
  const countdown = ref(5) // 倒计时总时长（秒）
  const countdownTimer = ref<number | null>(null)
  const endTime = ref<number>(0) // 使用结束时间戳替代开始时间戳，更直观

  // 初始化/重置倒计时
  const initCountdown = () => {
    // 清除旧定时器
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }

    // 计算结束时间（当前时间 + 180秒）
    endTime.value = Date.now() + 5 * 1000
    countdown.value = 5

    // 使用uni-app的setInterval，兼容性更好
    countdownTimer.value = setInterval(() => {
      const now = Date.now()
      const remaining = Math.ceil((endTime.value - now) / 1000)

      // 确保剩余时间不为负
      if (remaining <= 0) {
        countdown.value = 0
        if (countdownTimer.value) {
          clearInterval(countdownTimer.value)
          countdownTimer.value = null
        }
        uni.navigateBack() // 跳回上一页
      } else {
        countdown.value = remaining
      }
    }, 1000) as unknown as number // 类型转换，适配uni-app
  }

  onLoad((options: any) => {
    pointName.value = options.pointName
  })

  onMounted(() => initCountdown())

  // 组件卸载时强制清除定时器
  onUnmounted(() => {
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }
  })

  const onClick = () => {
    uni.navigateBack()
  }
</script>

<style scoped lang="scss">
  .time {
    position: absolute;
    top: 60rpx;
    right: 60rpx;
    color: #076bf2;
    font-size: 40rpx;
    .ret_text {
        color: #000000;;
    }
  }
  .success_img {
    margin: 0 auto;
    width: 200rpx;
    height: 200rpx;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .success_box {
    margin-top: 300rpx;
  }

  .succexx_text {
    font-size: 106rpx;
    text-align: center;
  }
  .success_label {
    color: #029b00;
    margin:60rpx 0;
  }
  .succexx_text1 {
  }
  .succexx_text2 {
    color: #f55535;
  }
</style>
